package com.sdruixinggroup.mondayb2b.ui;

import android.app.Activity;
import android.content.DialogInterface;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.widget.Toast;

import com.sdruixinggroup.mondayb2b.widget.CPProgressDialog;


/**
 * 基础fragment
 *
 * Created by czhang on 17/1/3.
 */
public class BaseFragment extends Fragment {
	/**
	 * toast提示
	 */
	private Toast mToast;

	/**
	 * 通用弹框
	 */
	private CPProgressDialog mDialog;

	/**
	 * toast提示
	 *
	 * @param msg
	 *            待提示内容
	 */
	protected void showToast(String msg) {
		Activity activity = getActivity();
		if (activity == null) {
			return;
		}
		if (activity instanceof BaseActivity) {
			// 优先使用宿主activity的toast
			((BaseActivity) activity).showToast(msg);
			return;
		}
		if (mToast == null) {
			mToast = Toast.makeText(activity, msg, Toast.LENGTH_SHORT);
		} else {
			mToast.setText(msg);
		}
		mToast.show();
	}

	/**
	 * 弹出对话框
	 *
	 * @param msg
	 *            待展示message
	 * @param isCancelable
	 *            是否可取消
	 * @param cancelListener
	 *            取消监听
	 */
	protected void showDialog(String msg, boolean isCancelable,
                              DialogInterface.OnCancelListener cancelListener) {
		Activity activity = getActivity();
		if (activity == null) {
			return;
		}
		dismissDialog();
		if (mDialog == null) {
			mDialog = new CPProgressDialog(activity);
		}
		if (!TextUtils.isEmpty(msg)) {
			mDialog.setMessage(msg);
		} else {
			mDialog.setMessage("");
		}
		mDialog.setCancelable(isCancelable);
		mDialog.setOnCancelListener(cancelListener);
		mDialog.show();
	}

	/**
	 * 弹对话框
	 * 
	 * @param msg
	 *            待提示内容
	 */
	protected void showDialog(String msg) {
		showDialog(msg, true, null);
	}

	/**
	 * dismiss对话框
	 */
	protected void dismissDialog() {
		if (mDialog != null && mDialog.isShowing()) {
			mDialog.dismiss();
		}
		mDialog = null;
	}

	@Override
	public void onDestroy() {
		dismissDialog();
		super.onDestroy();
	}

}
